package dice.sinanya.dice.manager;

import com.forte.qqrobot.beans.messages.result.inner.Group;
import com.forte.qqrobot.beans.messages.result.inner.GroupMember;
import com.forte.qqrobot.sender.MsgSender;
import dice.sinanya.db.ban.SelectBanList;
import dice.sinanya.entity.EntityTypeMessages;
import dice.sinanya.exceptions.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.nlpcn.commons.lang.util.StringUtil;

import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static dice.sinanya.system.MessagesBanList.groupBanList;
import static dice.sinanya.system.MessagesBanList.qqBanList;
import static dice.sinanya.system.MessagesTag.*;
import static dice.sinanya.tools.checkdata.CheckIsNumbers.isNumeric;
import static dice.sinanya.tools.getinfo.BanList.*;
import static dice.sinanya.tools.getinfo.GetMessagesProperties.entityBanProperties;
import static dice.sinanya.tools.makedata.MakeMessages.deleteTag;
import static dice.sinanya.tools.makedata.SendToMaster.sendToManager;
import static dice.sinanya.tools.makedata.Sender.sender;

/**
 * @author SitaNya
 * 日期: 2019-08-07
 * 电子邮箱: sitanya@qq.com
 * 维护群(QQ): 162279609
 * 有任何问题欢迎咨询
 * 类说明:
 */
public class BanList {
    private static final Logger log = LogManager.getLogger(BanList.class.getName());

    private final Pattern id = Pattern.compile("(\\d{4,15})[^\\d]*");
    private final EntityTypeMessages entityTypeMessages;
    private String Id;
    private String reason;

    public BanList(EntityTypeMessages entityTypeMessages) {
        this.entityTypeMessages = entityTypeMessages;
    }

    /**
     *
     */
    public void inputQqBanList() throws NotEnableBanException, CantInputBanException, BanMasterOrManagerGroupException {
        checkEnableBan();
        checkCanInputBan();
        String tag = TAG_BAN_USER;
        String msg = deleteTag(entityTypeMessages.getMsgGet().getMsg(), tag.substring(0, tag.length() - 2));

        makeId(msg);
        try {
            checkMaster();
            isQqOrGroup(Id);
            checkMaster(entityTypeMessages.getMsgSender(), Id);
            if (qqBanList.containsKey(Id)) {
                sender(entityTypeMessages, "用户:\t" + Id + "已在云黑名单中");
            } else {
                insertQqBanList(Id, reason);
                sendToManager(entityTypeMessages, "已将用户:\t" + Id + "加入云黑名单,理由为: " + reason + " 执行者为:\t" + entityTypeMessages.getFromQqString());
                sender(entityTypeMessages, "已将用户:\t" + Id + "加入云黑名单,理由为: " + reason);
            }
        } catch (BanListInputNotIdException | NotMasterException e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     *
     */
    public void inputGroupBanList() throws NotEnableBanException, CantInputBanException, BanMasterOrManagerGroupException {
        checkEnableBan();
        checkCanInputBan();
        String tag = TAG_BAN_GROUP;
        String msg = deleteTag(entityTypeMessages.getMsgGet().getMsg(), tag.substring(0, tag.length() - 2));
        makeId(msg);
        try {
            checkMaster();
            isQqOrGroup(Id);
            checkMaster(entityTypeMessages.getMsgSender(), Id);
            if (groupBanList.containsKey(Id)) {
                sender(entityTypeMessages, "群:\t" + Id + "已在云黑名单中");
            } else {
                insertGroupBanList(Id, reason);
                sendToManager(entityTypeMessages, "已将群:\t" + Id + "加入云黑名单,理由为: " + reason + " 执行者为:\t" + entityTypeMessages.getFromQqString());
                sender(entityTypeMessages, "已将群:\t" + Id + "加入云黑名单,理由为: " + reason);
            }
        } catch (BanListInputNotIdException | NotMasterException e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     *
     */
    public void rmQqBanList() throws NotEnableBanException {
        checkEnableBan();
        String tag = TAG_RM_BAN_USER;
        String msg = deleteTag(entityTypeMessages.getMsgGet().getMsg(), tag.substring(0, tag.length() - 4));
        try {
            checkMaster();
            isQqOrGroup(msg);
            if (qqBanList.containsKey(msg)) {
                removeQqBanList(msg, entityTypeMessages);
            } else {
                sender(entityTypeMessages, "用户:\t" + msg + "不在云黑名单中");
            }
        } catch (BanListInputNotIdException | NotBanListInputException | NotMasterException e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     *
     */
    public void rmGroupBanList() throws NotEnableBanException {
        checkEnableBan();
        String tag = TAG_RM_BAN_GROUP;
        String msg = deleteTag(entityTypeMessages.getMsgGet().getMsg(), tag.substring(0, tag.length() - 4));
        try {
            checkMaster();
            isQqOrGroup(msg);
            if (groupBanList.containsKey(msg)) {
                removeGroupBanList(msg, entityTypeMessages);
            } else {
                sender(entityTypeMessages, "群:\t" + msg + "不在云黑名单中");
            }
        } catch (BanListInputNotIdException | NotBanListInputException | NotMasterException e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     *
     */
    public void getQqBanList() throws NotEnableBanException {
        checkEnableBan();
        try {
            checkMaster();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("当前云黑内记录的黑名单用户列表如下，黑名单的刷新周期为15分钟，其他人新添加的黑名单可能暂时未同步");
            for (Map.Entry<String, String> mapEntry : qqBanList.entrySet()) {
                stringBuilder.append("\n").append(mapEntry.getKey());
            }
            sender(entityTypeMessages, stringBuilder.toString());
        } catch (NotMasterException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     *
     */
    public void getGroupBanList() throws NotEnableBanException {
        checkEnableBan();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("当前云黑内记录的黑名单群列表如下，黑名单的刷新周期为15分钟，其他人新添加的黑名单可能暂时未同步");
        for (Map.Entry<String, String> mapEntry : groupBanList.entrySet()) {
            stringBuilder.append("\n").append(mapEntry.getKey());
        }
        sender(entityTypeMessages, stringBuilder.toString());
    }

    public void isBan() throws BanListInputNotIdException, NotEnableBanException {
        checkEnableBan();
        String tag = TAG_BAN_CHECK;
        String msg = deleteTag(entityTypeMessages.getMsgGet().getMsg(), tag.substring(0, tag.length() - 4));
        if (!isNumeric(msg)) {
            throw new BanListInputNotIdException(entityTypeMessages);
        }
        SelectBanList selectBanList = new SelectBanList();
        try {
            checkMaster();
            ArrayList<String> banHistoryLists = new ArrayList<>();
            long id = Long.parseLong(msg);
            boolean isMaster = entityBanProperties.getMaster().contains(entityTypeMessages.getFromQqString());
            if (qqBanList.containsKey(msg)) {
                String qqHistory = selectBanList.selectQqBanInfo(id, isMaster);
                if (qqHistory != null) {
                    banHistoryLists.add(qqHistory);
                }
            }
            if (groupBanList.containsKey(msg)) {
                String groupHistory = selectBanList.selectGroupBanInfo(id, isMaster);
                if (groupHistory != null) {
                    banHistoryLists.add(groupHistory);
                }
            }
            ArrayList<String> historyList = selectBanList.selectBanHistory(msg);
            banHistoryLists.addAll(historyList);
            if (banHistoryLists.size() == 0) {
                sender(entityTypeMessages, "未找到与 " + msg + " 的有关记录");
            } else {
                sender(entityTypeMessages, "此记录下黑名单历史为:\n" + StringUtil.joiner(banHistoryLists, "\n"));
            }
        } catch (NotMasterException e) {
            log.error(e.getMessage(), e);
        }
    }

    private void isQqOrGroup(String input) throws BanListInputNotIdException {
        if (!isNumeric(input) || input.length() > 15 || input.length() < 4) {
            throw new BanListInputNotIdException(entityTypeMessages);
        }
    }

    private void checkMaster() throws NotMasterException {
        if (!entityBanProperties.getMaster().contains(String.valueOf(entityTypeMessages.getFromQqString()))) {
            sender(entityTypeMessages, "非master在使用命令，当前master为\n" + entityBanProperties.getMaster());
            throw new NotMasterException(entityTypeMessages);
        }
    }

    private void checkEnableBan() throws NotEnableBanException {
        if (!entityBanProperties.isCloudBan()) {
            throw new NotEnableBanException(entityTypeMessages);
        }
    }

    private void makeId(String msg) {
        Matcher qqMatcher = id.matcher(msg);
        if (qqMatcher.find()) {
            Id = qqMatcher.group(1);
            reason = msg.replace(Id, "").trim();
        } else if (isNumeric(msg)) {
            Id = msg;
            reason = "手工录入";
        } else {
            try {
                throw new BanListInputNotIdException(entityTypeMessages);
            } catch (BanListInputNotIdException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    private void checkCanInputBan() throws CantInputBanException {
        if (entityBanProperties.getMaster().size() == 0) {
            throw new CantInputBanException(entityTypeMessages);
        }
        String managerGroup = "162279609";
        boolean botInGroup = false;
        boolean masterInGroup = false;
        Group[] groups = entityTypeMessages.getMsgSender().GETTER.getGroupList().getList();
        for (Group group : groups) {
            if (group.getCode().equals(managerGroup)) {
                botInGroup = true;
                break;
            }
        }

        if (!botInGroup) {
            throw new CantInputBanException(entityTypeMessages);
        }

        GroupMember[] groupMembers = entityTypeMessages.getMsgSender().GETTER.getGroupMemberList(managerGroup).getList();

        for (GroupMember groupMember : groupMembers) {
            if (entityBanProperties.getMaster().contains(groupMember.getQQ())) {
                masterInGroup = true;
                break;
            }
        }

        if (!masterInGroup) {
            throw new CantInputBanException(entityTypeMessages);
        }
    }

    private void checkMaster(MsgSender msgSender, String qq) throws BanMasterOrManagerGroupException {
        if (entityBanProperties.getMaster().contains(qq)) {
            sendToManager(msgSender, "当前目标在Master列表内，停止拉黑");
            throw new BanMasterOrManagerGroupException();
        }
    }

}
